//
//
//

#import "UIButton+badge.h"

@implementation UIButton (badge)
- (void)showBadgeOnItemIndex:(int)index{
    //移除之前的小红点
    [self removeBadgeOnItemIndex:index];
    
    //新建小红点
    UIView *badgeView = [[UIView alloc]init];
    badgeView.tag = 888 + index;
    badgeView.layer.cornerRadius = 3;//圆形
    badgeView.backgroundColor = [UIColor redColor];//颜色：红色
    CGRect tabFrame = self.frame;
    
    //确定小红点的位置
    float percentX = (index +0.6) / 4;
    CGFloat x = ceilf(percentX * tabFrame.size.width);
    CGFloat y = ceilf(0.1 * tabFrame.size.height);
    badgeView.frame = CGRectMake(x, y, 6, 6);//圆形大小为10
    [self addSubview:badgeView];
}

- (void)hideBadgeOnItemIndex:(int)index{
    //移除小红点
    [self removeBadgeOnItemIndex:index];
}

- (void)removeBadgeOnItemIndex:(int)index{
    //按照tag值进行移除
    for (UIView *subView in self.subviews) {
        if (subView.tag == 888+index) {
            [subView removeFromSuperview];
        }
    }
}

- (void)showBadgeOnItemIndex:(int)index withNumber:(NSInteger)num{
    //移除之前的小红点
     [self removeBadgeOnItemIndex:index];
    //新建小红点
    UILabel *badgeView = [[UILabel alloc]init];
    badgeView.text = [NSString stringWithFormat:@"%ld",num];
    badgeView.textColor = [UIColor whiteColor];
    badgeView.font = [UIFont systemFontOfSize:10];
    badgeView.textAlignment = NSTextAlignmentCenter;
    badgeView.tag = 888 + index;
    badgeView.layer.cornerRadius = 8;//圆形
    badgeView.layer.masksToBounds = YES;
    badgeView.backgroundColor = [UIColor redColor];//颜色：红色
    CGRect tabFrame = self.frame;
    
    
    //确定小红点的位置
    float percentX = (index+0.2) / 4;
    CGFloat x = ceilf(percentX * tabFrame.size.width);
    CGFloat y = ceilf(0.025 * tabFrame.size.height);
    badgeView.frame = CGRectMake(x, -20, 15, 15);//圆形大小为10
    [self addSubview:badgeView];
}

@end
